// pages/project1/avatar/index.js
import http from '../../../utils/request'
import wechatToOss from '../../../utils/wechatToOss'
let videoAd = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cropper: null,
    width: 400, //宽度
    height: 400, //高度,
    marginLeft: 0,
    marginTop: 0,
    selectUrl: '',
    bgcImage: '',

    bgcShowSync: false,
    templateId: '',
    imageUrl: '',
    imageSize: 0,
    resultImg: '',

    PageNum: 1,
    PageSize: 10,
    templateList: [],
    isBottomAdd: true
  },

  pageList() {
    let params = {
      url: `/apng/pageFrame/${this.data.PageNum}/${this.data.PageSize}`,
      callBack: (res) => {
        if (res.data.list.length < this.data.PageSize) {
          this.setData({
            isBottomAdd: false
          })
        }
        this.setData({
          templateList: [...this.data.templateList, ...res.data.list]
        })
        if (!this.data.templateId) {
          this.setData({
            templateId: this.data.templateList[0].id,
            bgcImage: this.data.templateList[0].framePreview
          })
        }
      }
    };
    http.request(params);
  },

  addScroll() {
    if (this.data.isBottomAdd) {
      this.setData({
        PageNum: this.data.PageNum + 1
      });
      this.pageList();
    }
  },

  checkbgc(e) {
    this.setData({
      bgcImage: e.currentTarget.dataset.url,
      templateId: e.currentTarget.dataset.id
    })
  },

  cropperload(e) { },

  loadimage(e) {
    wx.hideLoading();
    //重置图片角度、缩放、位置
    this.data.cropper.imgReset();
  },

  chooseAvatar() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          selectUrl: res.tempFiles[0].tempFilePath
        })
      }
    })
  },

  cilckCreate() {
    wx.showModal({
      title: '提示',
      content: '观看广告后将立即生成图片，感谢您的支持与理解！',
      complete: (res) => {
        if (res.confirm) {
          if (videoAd) {
            videoAd.show().catch(() => {
              // 失败重试
              videoAd.load()
                .then(() => videoAd.show())
                .catch(err => {
                  console.error('激励视频 广告显示失败', err)
                })
            })

          }
        }
      }
    })
  },

  getCropperImg() {
    wx.showLoading({
      title: '内容校验中',
      mask: true
    })
    this.data.cropper.getImg((obj) => {
      this.madiaToOSS(obj.url)
    })
  },

  madiaToOSS(fileUrl) {
    const params = {
      filePath: fileUrl,
      formData: {
        type: 1,
      },
      callBack: (res) => {
        this.mergeApng(res)
      },
      errCallBack: (res) =>{
        this.setData({
          selectUrl:''
        })
      }
    };
    wechatToOss.uploadFile(params);
  },

  mergeApng(url) {
    wx.showLoading({
      title: '生成中',
      mask: true
    })
    let params = {
      url: `/apng/mergeApng`,
      data: {
        avatarUrl: url,
        frameId: this.data.templateId,
        type: 'gif'
      },
      callBack: (res) => {
        wx.hideLoading()
        this.setData({
          resultImg: res.data
        })
        wx.previewImage({
          urls: [res.data],
        })
      },
    };
    http.request(params);
  },

  lookresult() {
    wx.previewImage({
      urls: [this.data.resultImg],
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.pageList()
    this.setData({
      selectUrl: options.url,
    })
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-67c2975cdd6b7f05'
      })
      videoAd.onLoad(() => { })
      videoAd.onError((err) => {
        console.error('激励视频光告加载失败', err)
      })
      videoAd.onClose(res => {
        // 用户点击了【关闭广告】按钮
        if (res && res.isEnded) {
          this.getCropperImg()
        } else {
          wx.showToast({
            title: '未完整观看视频',
            icon: 'none'
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    setTimeout(() => {
      this.setData({
        bgcShowSync: true
      })
      this.data.cropper = this.selectComponent("#bgc-cropper");
    }, 1);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {

  // }
})